package com.yang.servlet;

import com.yang.pojo.Manager;
import com.yang.service.ManagerService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/LoginManagerServlet")
public class LoginManagerServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String loginName = request.getParameter("loginName");
        String loginPwd = request.getParameter("loginPwd");
        String checkCode = request.getParameter("checkCode");

        //拿到验证码的session
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute("code");
        //与输入的验证码进行对比，
        if(checkCode.equals(code)){
            //比较验证码正确与否才比较账户与密码
            ManagerService managerService = new ManagerService();
            try {
                Manager manager = managerService.checkLogin(loginName, loginPwd);
                if(manager == null){
                    //登陆失败：跳转到登录页面并进行错误提示
                    request.setAttribute("tips","<label style='color:red'>登录失败，账号或密码错误！</label>");
                    request.getRequestDispatcher("login.jsp").forward(request,response);
                }else {
                    session.setAttribute("mgr",manager);
                    String mgrId = manager.getMgrId();
                    session.setAttribute("mgrId",mgrId);
//                    response.sendRedirect("index.jsp");
                    response.sendRedirect("IndexServlet");


                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }else {
            request.setAttribute("tips","<label style='color:red'>验证码输入错误！</label>");
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }



    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
